import type { FormInstance, FormRules } from 'element-plus'
import { useUpdatepassword } from '~/api/manager/index'
// 修改密码
export const useRepassword = () => {
  const router = useRouter()
  const route = useRoute()
  const userStore = useUserStore()
  const { kDrawerRef, kDrawerOpen, kbDrawerClose, kDrawerBtnLoading } =
    useKDrawer()
  //密码修改参数
  const formRef = ref<FormInstance | null>(null)
  const passWordParmas = reactive({
    oldpassword: '',
    password: '',
    repassword: '',
  })
  // 修改密码规则
  const rules: FormRules = {
    oldpassword: [
      { required: true, message: '旧密码不能为空', trigger: 'blur' },
    ],
    password: [{ required: true, message: '新密码不能为空', trigger: 'blur' }],
    repassword: [
      { required: true, message: '确认密码不能为空 ', trigger: 'blur' },
    ],
  }
  // 修改方法
  const handleSubmit = () => {
    formRef.value!.validate(async (value: boolean) => {
      if (!value) return //如果不存在直接就结束
      kDrawerBtnLoading(true) //开启loading
      await useUpdatepassword(passWordParmas)
        .then(async () => {
          userStore.useLogoutfn().finally(() => {
            // 跳转登录页面
            router.push({
              name: 'login',
              query: { redirect: route.path },
            })
            ElNotification({
              message: '修改密码成功,请重新登录',
              type: 'success',
            })
          })
          kbDrawerClose() //关闭修改密码弹框
        })
        .finally(() => {
          kDrawerBtnLoading(false) //关闭loading
        })
    })
  }
  return {
    formRef,
    passWordParmas,
    rules,
    handleSubmit,
    kDrawerRef,
    kDrawerOpen,
    kbDrawerClose,
    kDrawerBtnLoading,
  }
}
// 退出登录
export const useOutLogin = () => {
  const router = useRouter()
  const route = useRoute()
  const userStore = useUserStore()
  //退出登录方法
  const handleLogOut = () => {
    ElMessageBox.confirm('此操作将退出登录, 是否继续?', '提示', {
      type: 'warning',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true //开启loading
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false //关闭loading
            }, 300)
          }, 700)
        } else {
          done()
        }
      },
    }).then(() => {
      userStore.useLogoutfn().finally(() => {
        // 跳转登录页面
        router.push({
          name: 'login',
          query: { redirect: route.path },
        })
        ElNotification({ title: '退出成功', type: 'success' }) //成功提示
      })
    })
  }
  return { handleLogOut }
}
